import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

function baseRouter(url, next) {

  let user = JSON.parse(sessionStorage.getItem('user')).menus_url
  let isfalg = user.some(item => item == url)
  if (isfalg) {
    next()
  }else{
    next('/home')
  }
}


export let apiurl = [

  {
    path: "/setshop",
    component: () => import('../views/setshop.vue'),
    name: '菜单管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/setshop",next)
    }
  },
  {
    path: "/setpeople",
    component: () => import('../views/setpeople.vue'),
    name: '角色管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/setpeople",next)
    }
  },
  {
    path: "/setmange",
    component: () => import('../views/setmange.vue'),
    name: '管理员管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/setmange",next)
    }
  },
  {
    path: "/toshop",
    component: () => import('../views/toshop.vue'),
    name: '商品分类',
    beforeEnter: (to, from, next) => {
      baseRouter("/toshop",next)
    },
  },
  {
    path: "/tobanner",
    component: () => import('../views/banner.vue'),
    name: '轮播图管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/tobanner",next)
    },
  },
  {
    path: "/tospecs",
    component: () => import('../views/specs.vue'),
    name: '商品规格管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/tospecs",next)
    },
  },
  {
    path: "/togoods",
    component: () => import('../views/goods.vue'),
    name: '商品管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/togoods",next)
    },
  },
  {
    path: "/touser",
    component: () => import('../views/user.vue'),
    name: '会员管理',
    beforeEnter: (to, from, next) => {
      baseRouter("/touser",next)
    },
  },
  {
    path: "/toseck",
    component: () => import('../views/seck.vue'),
    name: '限时秒杀',
    beforeEnter: (to, from, next) => {
      baseRouter("/toseck",next)
    },
  },
]

const routes = [{
    path: "/login",
    component: () => import("../pages/login")
  },
  {
    path: "/index",
    component: () => import("../pages/index"),
    children: [{
        path: "/home",
        component: () => import('../views/home.vue')
      },
      ...apiurl,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: "*",
    redirect: '/login'
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{
  if(to.path=='/login'){
    next()
    return
  }
  if(sessionStorage.getItem('user')){
    next()
    return
  }
  next('/login')
})

export default router